<template>
    <div class="container py-4">
        <!-- 新增按钮 -->
        <button class="btn btn-primary mb-3" @click="openAddModal">新增分类</button>

        <!-- loading 状态 -->
        <Skeleton v-if="categoryLoading" :rows="6" :lines="2" :show-avatar="true" />
        <!-- 分类列表展示 -->
        <div v-else-if="categories.length" class="list-group">
            <div v-for="cat in categories" :key="cat.id"
                class="list-group-item d-flex justify-content-between align-items-center">
                <!-- 左侧：图标 + 名称 -->
                <div class="d-flex align-items-center gap-3">
                    <i :class="[cat.icon, cat.color]" style="font-size: 1.2rem"></i>
                    <strong>{{ cat.name }}</strong>
                </div>

                <!-- 右侧：操作按钮 -->
                <div class="d-flex gap-2">
                    <button class="btn btn-sm btn-outline-secondary" @click="editCategory(cat)">编辑</button>
                    <button class="btn btn-sm btn-outline-danger" @click="openDeleteModal(cat)">删除</button>
                </div>
            </div>
        </div>

        <!-- 空状态 -->
        <EmptyState v-else icon="📂" title="暂无分类" description="你还没有创建任何分类" />

        <!-- ✅ 新增/编辑模态框 -->
        <Modal v-model:show="showForm" title="分类编辑">
            <CategoryForm :initial-data="editing" @saved="onSaved" @cancel="showForm = false" />
        </Modal>

        <!-- ✅ 删除确认模态框 -->
        <Modal v-model:show="showDeleteModal" title="确认删除">
            <div class="d-flex align-items-center gap-3">
                <i class="bi bi-exclamation-triangle-fill text-danger fs-2"></i>
                <p class="mb-0 fw-semibold">确定删除分类「{{ deletingItem?.name }}」吗？删除后不可恢复！</p>
            </div>
            <template #footer>
                <button class="btn btn-secondary me-2" @click="showDeleteModal = false" :disabled="deleting">取消</button>
                <button class="btn btn-danger" @click="confirmDelete" :disabled="deleting">
                    <span v-if="deleting" class="spinner-border spinner-border-sm me-2"></span>
                    删除
                </button>
            </template>
        </Modal>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';

import Modal from '../components/Modal.vue';
import EmptyState from '../components/ui/EmptyState.vue';
import CategoryForm from '../components/CategoryForm.vue';
import Skeleton from '../components/ui/Skeleton.vue';

import { useApi } from '../composables/useApi';
import { useToast } from '../composables/useToast';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../store/auth';

const router = useRouter();
const auth = useAuthStore();
const { success, error, warning } = useToast();

// ✅ 模态框控制
const showForm = ref(false); // 控制新增/编辑模态框
const editing = ref(null); // 当前编辑的分类数据

const showDeleteModal = ref(false); // 控制删除确认模态框
const deletingItem = ref(null); // 当前准备删除的分类
const deleting = ref(false); // 删除状态 loading

// ✅ 获取分类数据
const {
    result: categoriesResult,
    fetchData: fetchCategories,
    loading: categoryLoading
} = useApi({
    url: '/transactions/search/category',
    method: 'GET',
    transform: res => res.data,
    manual: true
});

// ✅ 安全处理避免 categories 为空或不是数组
const categories = computed(() => (Array.isArray(categoriesResult.value) ? categoriesResult.value : []));

// ✅ 点击新增分类
function openAddModal() {
    editing.value = null;
    showForm.value = true;
}

// ✅ 点击编辑分类
function editCategory(cat) {
    editing.value = { ...cat };
    showForm.value = true;
}

// ✅ 表单保存后刷新列表并关闭弹窗
function onSaved() {
    showForm.value = false;
    editing.value = null;
    fetchCategories();
}

// ✅ 点击删除按钮，打开删除确认模态框
function openDeleteModal(cat) {
    deletingItem.value = cat;
    showDeleteModal.value = true;
}

// ✅ 执行删除
async function confirmDelete() {
    if (!deletingItem.value) return;

    deleting.value = true;
    try {
        // 使用已有的useApi实例而不是创建新的
        await useApi({
            url: `/transactions/delete/category/${deletingItem.value.id}`,
            method: 'DELETE',
            toast: true
        }).fetchData();

        success('删除成功！');
        showDeleteModal.value = false;
        deletingItem.value = null;
        fetchCategories();
    } catch (err) {
        console.error('删除分类失败:', err);
        error('删除失败: ' + (err.response?.data?.message || err.message || '未知错误'));
    } finally {
        deleting.value = false;
    }
}

// ✅ 初始化加载
onMounted(async () => {
    try {
        await fetchCategories();
    } catch (err) {
        console.error('获取分类失败:', err);
        if (err.response?.status === 401) {
            auth.clearToken();
            router.push('/login');
            error('登录已过期，请重新登录');
        } else {
            warning('获取分类失败: ' + (err.response?.data?.message || err.message || '未知错误'));
        }
    }
});
</script>